package net.csdn.business.kanban.feign.config;


import io.opentracing.Tracer;
import net.csdn.business.kanban.feign.config.properties.FeignAuthProperties;
import net.csdn.business.kanban.feign.interceptor.AuthFeignClientInterceptor;
import net.csdn.business.kanban.feign.interceptor.GitCodeFeignInterceptor;
import okhttp3.ConnectionPool;
import okhttp3.Dispatcher;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.support.FeignHttpClientProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
/*@ConditionalOnClass(Feign.class)*/
@EnableConfigurationProperties(FeignAuthProperties.class)
//@ImportAutoConfiguration({SecurityInnerAspect.class})
public class FeignOkHttpConfig {
    @Autowired
    private FeignHttpClientProperties feignHttpClientProperties;


    @Value("${feign.ok.http.connect-timeout:30}")
    private Integer connectTimeout;

    @Value("${feign.ok.http.read-timeout:60}")
    private Integer readTimeout;

    @Value("${feign.ok.http.write-timeout:120}")
    private Integer writeTimeout;

    @Value("${feign.ok.http.max-idle-connections:200}")
    private Integer maxIdleConnections;

    @Value("${feign.ok.http.keep-alive-duration:300}")
    private Long keepAliveDuration;


    @Autowired(required = false)
    private Tracer tracer;

    @Autowired
    private FeignAuthProperties feignAuthConfig;

    @Bean
    public AuthFeignClientInterceptor authFeignClientInterceptor() {
        return new AuthFeignClientInterceptor(feignAuthConfig);
    }

    @Bean
    @ConditionalOnProperty(value = "service.type",havingValue = "gitcode")
    public GitCodeFeignInterceptor gitCodeFeignInterceptor() {
        return new GitCodeFeignInterceptor();
    }

    @Bean
    public OkHttpClient.Builder okHttpClientBuilder() {
        Dispatcher dispatcher = new Dispatcher();
        dispatcher.setMaxRequests(feignHttpClientProperties.getMaxConnections());
        dispatcher.setMaxRequestsPerHost(feignHttpClientProperties.getMaxConnectionsPerRoute());
        return new OkHttpClient.Builder()
                .dispatcher(dispatcher)
                .readTimeout(readTimeout, TimeUnit.SECONDS)
                .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .connectionPool(pool())
                /*.addInterceptor(new SysLogTraceHeaderInterceptor(tracer))*/;
    }


    public ConnectionPool pool() {
        return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
    }


}